# -*- coding:utf-8 -*-


import os
import ConfigParser


class Config:
    """
        操作config.ini文件
    """
    def __init__(self, path="config.ini"):
        self.path = path
        self.cf = ConfigParser.ConfigParser()
        self.initialize_ini()
        # self.cf.open(self.path, "w+")
        self.cf.read(self.path)

    def get(self, field, key):
        try:
            result = self.cf.get(field, key)
        except Exception as e:
            print "get config item fail:", e
            result = ""
        return result

    def set(self, field, key, value):
        try:
            self.cf.set(field, key, value)
            self.cf.write(open(self.path, 'w'))
        except Exception as e:
            print "set config item fail:", e
            return False
        return True

    def initialize_ini(self):
        """如果文件不存在则创建默认配置的文件，或提示出错"""
        if not os.path.exists(self.path):
            "设置section段及对应的值"
            cf = ConfigParser.ConfigParser()

            "filter mode, 记录上次使用的模式"
            cf.add_section("logcat")
            cf.set("logcat", "mode", "")

            "写入文件"
            cf.write(open(self.path, "w"))

    @staticmethod
    def read_config(config_file_path, field, key):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(config_file_path)
            result = cf.get(field, key)
        except Exception as e:
            print "read config file fail:", e
            result = ""
        return result

    def read_path_config(self, field, key):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(self.path)
            result = cf.get(field, key)
            if result.startswith("\\"):
                result = result[1:]
            if not result.endswith("\\"):
                result += "\\"
        except Exception as e:
            print "read path from config file fail:", e
            result = ""
        return result

    @staticmethod
    def write_config(config_file_path, field, key, value):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(config_file_path)
            cf.set(field, key, value)
            cf.write(open(config_file_path, 'w'))
        except Exception as e:
            print "write config file fail:", e
            return False
        return True

if __name__ == "__main__":
    pass
